package com.gocoolmall.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.gocoolmall.common.exception.NoStockException;
import com.gocoolmall.common.to.mq.OrderTo;
import com.gocoolmall.common.to.mq.SeckillOrderTo;
import com.gocoolmall.common.utils.R;
import com.gocoolmall.common.vo.MemberRespVo;
import com.gocoolmall.order.constant.OrderConstant;
import com.gocoolmall.order.entity.OrderItemEntity;
import com.gocoolmall.order.entity.PaymentInfoEntity;
import com.gocoolmall.order.enume.OrderStatusEnum;
import com.gocoolmall.order.feign.CartFeignService;
import com.gocoolmall.order.feign.MemberFeignServier;
import com.gocoolmall.order.feign.ProductFeignService;
import com.gocoolmall.order.feign.WmsFeignService;
import com.gocoolmall.order.interceptor.LoginUserInterceptorRegistry;
import com.gocoolmall.order.service.OrderItemService;
import com.gocoolmall.order.service.PaymentInfoService;
import com.gocoolmall.order.to.OrderCreateTo;
import com.gocoolmall.order.vo.*;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gocoolmall.common.utils.PageUtils;
import com.gocoolmall.common.utils.Query;

import com.gocoolmall.order.dao.OrderDao;
import com.gocoolmall.order.entity.OrderEntity;
import com.gocoolmall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    private  ThreadLocal<OrderSubmitVO> confirmVoThreadLocal = new ThreadLocal<>();

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    MemberFeignServier memberFeignServier;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    WmsFeignService wmsFeignService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVO confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVO confirmVO = new OrderConfirmVO();
        MemberRespVo memberRespVo = LoginUserInterceptorRegistry.loginUser.get();
        System.out.println("主线程ID"+Thread.currentThread().getId());

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();


        CompletableFuture<Void> getAdressFuture = CompletableFuture.runAsync(() -> {
            System.out.println("Adress线程"+Thread.currentThread().getId());
            //每个线程都进来共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //1、远程查询所有的收货地址列表
            System.out.println("收货地址上送：："+memberRespVo.getId());
            List<MemberAddressVO> address = memberFeignServier.getAddress(memberRespVo.getId());
            System.out.println("收货地址"+address);
            confirmVO.setAddress(address);
        }, executor);

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            System.out.println("cart线程"+Thread.currentThread().getId());
            //每个线程都进来共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //2、远程查询购物所有选择中的购物项。
            List<OrderItemVo> orderItems = cartFeignService.getCurrentUserCartItems();
            System.out.println("的购物项。"+orderItems);
            confirmVO.setItem(orderItems);
        }, executor).thenRunAsync(() ->{
            //查询库存信息
            List<OrderItemVo> items = confirmVO.getItem();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            //TODO 一定要启动库存服务，否则库存查不出。
            R skuHasStock = wmsFeignService.getSkuHasStock(collect);
            List<SkuStockVo> date = skuHasStock.getDate(new TypeReference<List<SkuStockVo>>(){});
            if (date != null){
                Map<Long, Boolean> map = date.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                confirmVO.setStocks(map);
            }
        },executor);

        //3、查询用户积分
        Integer integration = memberRespVo.getIntegration();
        confirmVO.setIntegeration(integration);

        //4、其他数据自动计算

        //TODO 5、防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        //redis中存入token
        // K key,键
        // V value,值
        // final long timeout,过期时间
        // final TimeUnit unit,单位
//        TimeUnit.DAYS          //天
//        TimeUnit.HOURS         //小时
//        TimeUnit.MINUTES       //分钟
//        TimeUnit.SECONDS       //秒
//        TimeUnit.MILLISECONDS  //毫秒
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId(),token,30, TimeUnit.MINUTES);
        String key = OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId();
        System.out.println("上送redis的数据key:"+key+"value:"+token);
        confirmVO.setOrderToken(token);


        CompletableFuture.allOf(getAdressFuture, cartFuture).get();
        return confirmVO;
    }

    /**
     * 事务。
     * 本地事务，在分布式系统，只能控制自己的回滚，控制不了其他服务的回滚。
     * 分布式事务：最大的原因，网络问题+分布式机器
     *    开启全局事务
     *    @GlobalTransactional
     *
     * @param orderSubmitVO
     * @return
     */

    @GlobalTransactional  //高并发
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVO orderSubmitVO) {
        confirmVoThreadLocal.set(orderSubmitVO);
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        MemberRespVo memberRespVo = LoginUserInterceptorRegistry.loginUser.get();
        responseVo.setCode(0);
        //1、验证令牌
        //0 令牌失败  1 删除成功
        String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then return redis.call(\"del\",KEYS[1]) else return 0 end";
        String orderToken = orderSubmitVO.getOrderToken();
        System.out.println("orderToke:"+orderToken);
       String key = OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId();
        System.out.println("rediskey::"+key);
        //原子验证令牌和删除令牌
        Long result = redisTemplate.execute(
                new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()),
                orderToken);
        System.out.println("原子验证结果："+result);
        if (result == 0L){
            //令牌验证失败
            System.out.println("令牌验证失败");
            responseVo.setCode(1);
            return responseVo;
        }else {
            //令牌验证通过
            //去创建订单，验令牌，验价格，锁库存。。。
            //1、创建订单，订单项等信息
            OrderCreateTo order = createOrder();

            //2、验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = orderSubmitVO.getPayPrice();
            if (Math.abs( payAmount.subtract(payPrice).doubleValue()) < 0.01){
                //金额对比成功
                //。。。。
                //3、保存订单
                saveOrder(order);
                //4、库存锁定，只要有异常回滚订单数据
                //订单号，所有的订单项（sku,skuname,num)
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setCount(item.getSkuQuantity());
                    itemVo.setTitle(item.getSkuName());
                    return itemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(locks);
                //todo 4、远程锁库存
                //库存成功了但是网络原因超时了，订单回滚，库存不滚。
                //为了保保证高并发，库存服务自己回滚。可以发消息给库存服务；
                //库存服务本身页可以使用自动解锁模式 消息
                R r = wmsFeignService.orderLockStock(wareSkuLockVo);
                if (r.getCode() ==0){
                    //锁定成功
                    responseVo.setOrder(order.getOrder());
                    //TODO 5、远程扣积分，出现异常
                    //int i = 10/0;//订单回滚，库存不回滚
                    //TODO 订单创建成功发送消息MQ
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
                    return responseVo;
                }else {
                    //锁定失败
                    Long msg = (Long) r.get("msg");
                    throw new NoStockException(msg);
                }

            }else {
                responseVo.setCode(2);
                return responseVo;
            }

        }


//        String redis_token = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId());
//        if (orderToken != null && orderToken.equals(redis_token)){
//            //令牌验证通过
//        }else {
//            //不通过
//        }
    }

    @Override
    public OrderEntity getOrderStatus(String orderSn) {
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn",orderSn));
    }

    @Override
    public void closeOrder(OrderEntity entity) {
        //
        OrderEntity orderEntity = this.getById(entity.getId());
        if (orderEntity.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()){
            //关单
            OrderEntity update = new OrderEntity();
            update.setId(entity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity,orderTo);
            //关闭订单成功一个一个成功的MQ
            try {
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
            } catch (AmqpException e) {
                //TODO 将没有发送成功的消息
                e.printStackTrace();
            }
        }
    }

    /**
     *获取当前的支付信息
     * @param orderSn
     * @return
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity orderEntity = this.getOrderStatus(orderSn);

        BigDecimal decimal = orderEntity.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(decimal.toString());
        payVo.setOut_trade_no(orderEntity.getOrderSn());

        List<OrderItemEntity> orderSnList = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        System.out.println("订单详细"+orderSnList);
        OrderItemEntity itemEntity = orderSnList.get(0);
        payVo.setSubject(itemEntity.getSkuName());
        payVo.setBody(itemEntity.getSkuAttrsVals());

        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptorRegistry.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",memberRespVo.getId()).orderByDesc("id")
        );
        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> order_List = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_Sn", order.getOrderSn()));
            order.setItemEntities(order_List);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(order_sn);
        return new PageUtils(page);
    }

    /**
     * 处理支付宝返回的结果
     * @param vo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        //1、保存交流水
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setAlipayTradeNo(vo.getTrade_no());
        paymentInfoEntity.setOrderSn(vo.getOut_trade_no());
        paymentInfoEntity.setPaymentStatus(vo.getTrade_status());
        paymentInfoEntity.setCallbackTime(vo.getNotify_time());

        paymentInfoService.save(paymentInfoEntity);
        //2、修改订单的状态信息
        if (vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")){
            //支付宝成功状态
            String outTradeNo = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(outTradeNo,OrderStatusEnum.PAYED.getCode());

        }
        
        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo entity) {
        //TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(entity.getOrderSn());
        orderEntity.setMemberId(entity.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());

        BigDecimal multiply = entity.getSeckillPrice().multiply(new BigDecimal("" + entity.getNum()));
        orderEntity.setPayAmount(multiply);
        this.save(orderEntity);
        //保存订单项信息
        OrderItemEntity itemEntity = new OrderItemEntity();
        itemEntity.setOrderSn(entity.getOrderSn());
        itemEntity.setRealAmount(multiply);
        //TODO 获取当前SKU的订单信息进行设置
        itemEntity.setSkuQuantity(entity.getNum());
        orderItemService.save(itemEntity);
    }


    /**
     * 保存订单数据
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }


    //创建订单
    private OrderCreateTo createOrder( ){
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        //1、生成订单号
        String timeId = IdWorker.getTimeId();
        //创建订单号
        OrderEntity orderEntity = buildOrder(timeId);

        //2、获取到所有的订单项
        List<OrderItemEntity> itemEntities = buildOrderItems(timeId);

        //3、验价:计算价格,积分等相关
        computerPrice(orderEntity,itemEntities);
        System.out.println("计算:"+orderEntity);
        orderCreateTo.setOrder(orderEntity);
        orderCreateTo.setOrderItems(itemEntities);

        return orderCreateTo;
    }

    private void computerPrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");//优惠劵
        BigDecimal promotinAmount = new BigDecimal("0.0");//打折
        BigDecimal integretionAmount = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0.0");//总积分
        BigDecimal growth = new BigDecimal("0.0");//总成长值
        for (OrderItemEntity entity : itemEntities) {
            coupon = coupon.add(entity.getCouponAmount());
            integretionAmount =integretionAmount.add(entity.getIntegrationAmount());
            promotinAmount = promotinAmount.add(entity.getPromotionAmount());
            total = total.add(entity.getRealAmount());
            gift=gift.add(new BigDecimal(entity.getGiftIntegration().toString()));
            growth=growth.add(new BigDecimal(entity.getGiftGrowth().toString()));
        }
        //1、订单价格的相关
        orderEntity.setTotalAmount(total);
        //应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setIntegrationAmount(integretionAmount);
        orderEntity.setCouponAmount(coupon);
        orderEntity.setPromotionAmount(promotinAmount);

        //设置积分等信息
        orderEntity.setIntegration(gift.intValue());//
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setDeleteStatus(0); //未删除
        
    }


    /**
     *创建订单号
     * @param timeId
     * @return
     */
    private OrderEntity buildOrder(String timeId) {
        MemberRespVo memberRespVo = LoginUserInterceptorRegistry.loginUser.get();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(timeId);
        orderEntity.setMemberId(memberRespVo.getId());

        //获取收货地址
        OrderSubmitVO submitVO = confirmVoThreadLocal.get();
        R fare = wmsFeignService.getFare(submitVO.getAddrId());
        FareVo fareResp = fare.getDate(new TypeReference<FareVo>() {
        });

        //设置运费信息
        orderEntity.setFreightAmount(fareResp.getFare());
        //设置收货人信息
        orderEntity.setReceiverCity(fareResp.getAddress().getCity());
        orderEntity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
        orderEntity.setReceiverName(fareResp.getAddress().getName());
        orderEntity.setReceiverPhone(fareResp.getAddress().getPhone());
        orderEntity.setReceiverPostCode(fareResp.getAddress().getPostCode());
        orderEntity.setReceiverProvince(fareResp.getAddress().getProvince());
        orderEntity.setReceiverRegion(fareResp.getAddress().getRegion());

        //设置订单的相关状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());//订单状态
        orderEntity.setAutoConfirmDay(7);//自动收货时间 7

        return orderEntity;
    }

    /**
     * 构建所有订单项数据
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        System.out.println("构建所有订单项数据orderSn:"+orderSn);
        //最后确定每个购物项的价格
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        System.out.println("每个购物项的价格:"+ JSONObject.toJSONString(currentUserCartItems));
        if (currentUserCartItems != null && currentUserCartItems.size() >0){
            List<OrderItemEntity> itemEntities = currentUserCartItems.stream().map(cartItem -> {
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }

    /**
     * 构建某个订单项数据
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem){
        OrderItemEntity itemEntity = new OrderItemEntity();
        //1、订单信息：订单号
        System.out.println("订单号:::"+cartItem);
        //2、商品的SPU信息  v
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo date = r.getDate(new TypeReference<SpuInfoVo>() {
        });
        itemEntity.setSpuId(date.getId());
        itemEntity.setSpuBrand(date.getBrandId().toString());
        itemEntity.setSpuName(date.getSpuName());
        itemEntity.setCategoryId(date.getCatalogId());

        //3、商品的sku信息  v
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPrice(cartItem.getPrice());
        itemEntity.setSkuPic(cartItem.getImage());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        //4、优惠信息[不做]

        //5、积分信息
        //成长值
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        //积分
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());

        //6、订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));//商品促销分解金额
        itemEntity.setCouponAmount(new BigDecimal("0"));//优惠券优惠分解金额
        itemEntity.setIntegrationAmount(new BigDecimal("0"));//积分优惠分解金额
        //当前订单项的实际金额，总额-各种优惠
        BigDecimal orign = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal subtract = orign.subtract(itemEntity.getPromotionAmount()).
                subtract(itemEntity.getCouponAmount()).
                subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(subtract);


        return itemEntity;
    }

}

